<?php
// 应用公共文件
use think\facade\Db;
use think\facade\Cache;

// 应用公共文件
if(!function_exists('json_return')){
    /**
     * 通用json返回
     *
     * @param string $status
     * @param string $msg
     * @param array $data
     * @param array $other
     * @return json
     */
    function json_return($status = '10000', $msg = '操作成功', $data = [], $other = [])
    {
        $arr = [
            'status' => $status,
            'data' => $data,
            'msg' => $msg
        ];
        if($other){
            $arr = array_merge($arr, $other);
        }
        return $arr;
    }
}
if(!function_exists('json_redirect')){
    /**
     * 带跳转地址的json返回
     *
     * @param string $url
     * @return json
     */
    function json_redirect($url = '')
    {
        return json_return('10000', '', '', [
            'redirect' => $url ? $url : (!empty(request()->param['jumpUrl']) ? urldecode(request()->param['jumpUrl']) : '/')
        ]);
    }
}

if(!function_exists('get_path_info')){
    /**
     * 只有通过pathinfo才能获取到模型、控制器、方法
     *
     * @return array
     */
    function get_path_info($lower = false)
    {
        list($module, $controller, $action) = explode('/', preg_replace("/^\/+/", "", request()->baseUrl()));
        if($lower){
            $module = strtolower($module);
            $controller = strtolower($controller);
            $action = strtolower($action);
        }
        return [$module, $controller, $action];
        // $temp = explode('/', request()->pathinfo());
        // if(count($temp) == 1){
        //     $module = 'index';
        //     $controller = 'index';
        //     $action = 'index';
        // }elseif(count($temp) == 2){
        //     $module = $lower ? strtolower($temp[0]) : $temp[0];
        //     $controller = $lower ? strtolower($temp[1]) : $temp[1];
        //     $action = 'index';
        // }else{
        //     $module = $lower ? strtolower($temp[0]) : $temp[0];
        //     $controller = $lower ? strtolower($temp[1]) : $temp[1];
        //     $action = $lower ? strtolower($temp[2]) : $temp[2];
        // }
        // return [$module, $controller, $action];
    }
}

if(!function_exists('get_database_info')){
    /**
     * 根据模型和ID，过滤隐藏字段后返回
     * 
     * @param str $modelUrl
     * @param int $id
     * @param array $hidden
     * 
     * @return json
     */
    function get_admin_database_info($table, $id, $hidden = [])
    {
        if(!$id){
            return json_return('10001', '参数为空');
        }
        if(file_exists(\think\facade\App::getRootPath().'app/admin/model/'.ucfirst($table).'.php')){
            $name = '\\app\\admin\\model\\'.ucfirst($table);
            $model = new $name;
            try{
                $fliterField = [];
                foreach($hidden as $v){
                    $fliterField[] = $v;
                }
                if(isset($model->fliterField)){
                    foreach($model->fliterField as $v){
                        $fliterField[] = $v;
                    }
                }
            }catch(\Exception $e){

            }
        }else{
            $model = Db::name($table);
            $fliterField = $hidden;
        }
        $result = $model->where('id', $id)->withoutField($fliterField)->find();
        if(!$result){
            return json_return('10002', '参数错误');
        }
        if(is_object($result)){
            $result = $result->toArray();
        }
        foreach($result as $k => $v){
            if(preg_match('/.*?_img$/', $k)){
                $result[$k.'file'] = getFile($v);
            }
        }
        return json_return('10000', '', $result);
    }
}

if(!function_exists('check_field_repeat')){
    /**
     * 判断对应字段的数据是否存在
     *
     * @param string $table
     * @param string $field
     * @param string $fieldName
     * @return string/boolean
     */
    function check_field_repeat($table = '', $field = '', $fieldName = '')
    {
        $where = [[$field, '=', request()->post($field)]];
        if(request()->post('id', null)){
            $where[] = ['id', '<>', request()->post('id')];
        }
        $r = Db::name($table)->where($where)->find();
        return $r ? $fieldName.'已经存在' : true;
    }
}

if(!function_exists('check_permission'))
{
    /**
     * 权限验证
     *
     * @param string $module
     * @param string $controller
     * @param string $action
     * @return boolean/string
     */
    function checkPermission($module = '', $controller = '', $action = '')
    {
        if(!$module &&!$controller &&!$action){
            list($module, $controller, $action) = get_path_info(true);
        }
        $admin = Cache::get(request()->header()['token']??'');
        if($admin['is_system']){
            return 'system';
        }
        if(count($admin['role_ids']) == 0){
            return false;
        }
        $roles = (new \app\admin\model\Role)->where('id', 'in', $admin['role_ids'])->where('site_id', Db::name('site')->where('host', str_replace('admin.', '', $_SERVER['HTTP_HOST']) ?? '')->value('id'))->column('permission_ids');
        $temp = [];
        foreach($roles as $v){
            $temp1 = json_decode($v, true);
            foreach($temp1 as $v1){
                $temp[] = $v1;
            }
        }
        $permissions = (new \app\admin\model\Permission)->where('id', 'in', $temp)->select()->toArray();
        foreach($permissions as $v){
            if(strtolower($v['module']) == strtolower($module) && strtolower($v['controller']) == strtolower($controller) && strtolower($v['action']) == strtolower($action)){
                return true;
            }
        }
        return false;
    }
}

/**
 * 获取文件地址
 * @param int $id
 * @return string
 */
if(!function_exists('getFile')){
    function getFile($id){
        $file = Db::name('files')->where('id', $id)->find();
        if(!$file){
            return '';
        }
        $url = '';
        switch($file['upload_type']){
            case 'cos':
                $conf = config('cos.');
                $cosClient = new \Qcloud\Cos\Client([
                    'region' => $conf['COS_REGION'],
                    'credentials'=> [
                        'appId' => $conf['COS_APPID'],
                        'secretId'    => $conf['COS_KEY'],
                        'secretKey' => $conf['COS_SECRET']
                    ]
                ]);
                $url = $cosClient->getObjectUrl($conf['COS_BUCKET'], $file['file_path']);
                break;
            case 'local':
                $url = $file['file_path'];
                break;
        }
        return $url;
    }
}

/**
 * 获取字段类型
 * @param string $table
 * @param string $field
 * @param string $value
 * @return array
 */
if(!function_exists('getFieldType')){
    function getFieldType($table, $field, $value = ''){
        $temp = [
            'title' => explode('：', $field['Comment'])[0],
            'key' => $field['Field'],
            'value' => $value,
        ];
        if($field['Field'] == 'pid'){//父ID，目前只支持1级
            $temp['type'] = 'select';
            $a = Db::name($table)->where('pid', '=', 0)->field('id, title')->select();
            $temp['list'] = [
                0 => [
                    'id' => 0,
                    'title' => '无'
                ]
            ];
            foreach($a as $v1){
                $temp['list'][] = $v1;
            }
        }elseif(preg_match('/tinyint/', $field['Type'])){
            $a = explode('；', explode('：', $field['Comment'])[1]);
            $temp['type'] = 'select';
            $temp['list'] = [
                0 => [
                    'id' => 0,
                    'title' => '全部'
                ]
            ];
            foreach($a as $v1){
                $temp1 = explode('、', $v1);
                $temp['list'][] = [
                    'title' => $temp1[1],
                    'id' => $temp1[0]
                ];
            }
        }elseif(preg_match('/varchar/', $field['Type'], $a)){
            $temp['type'] = 'text';
        }elseif(preg_match('/char/', $field['Type']) && preg_match('/日期/', $field['Comment'])){
            //日期处理
            if(preg_match('/日期/', $field['Comment'])){
                $temp['type'] = 'date';
            }else{
                $temp['type'] = 'text';
            }
        }elseif(preg_match('/double/', $field['Type']) || preg_match('/float/', $field['Type']) || preg_match('/decimal/', $field['Type'])){
            $temp['type'] = 'number';
            $temp['step'] = 0.01;
        }elseif(preg_match('/int/', $field['Type'])){
            if(preg_match('/_id$/', $field['Field'])){//以ID结束的字段表示是关联数据
                $temp['type'] = 'select';
                $fields = 'id, title';
                if(str_replace('_id', '', $field['Field']) == 'user'){//用户表特殊处理
                    $fields = 'id, nickname as title';
                }
                try{
                    $a = Db::name(str_replace('_id', '', $field['Field']))->field('id, title, pid')->select();
                }catch(\Exception $e){
                    $a = Db::name(str_replace('_id', '', $field['Field']))->field($fields)->select();
                }
                $temp['list'] = [
                    0 => [
                        'id' => 0,
                        'title' => '无',
                        'pid' => 0
                    ]
                ];
                foreach($a as $v1){
                    $temp['list'][] = $v1;
                }
            }else{
                $temp['type'] = 'text';
                $temp['step'] = 1;
            }
        }elseif(preg_match('/text/', $field['Type']) || preg_match('/longtext/', $field['Type'])){
            if(preg_match('/_ids/', $field['Field'])){//以IDS结束的字段表示是多项关联
                $temp['type'] = 'checkbox';
                $temp['list'] = Db::name(str_replace('_ids', '', $field['Field']))->field('id, title')->select();
            }else{
                $temp['type'] = 'editor';
            }
        }
        return $temp;
    }
}